import {Component, OnInit, ViewChild, ElementRef, Renderer2} from '@angular/core';
import {FundFavoriteService} from "./fund-favorite.service";
import {FundFavoriteDetailModel, FundFavoriteModel, FundModel} from "./fund-favorite.model";
import {Subscription} from "rxjs/Subscription";
import {Util} from "../../common/util";
import {Observable} from "rxjs/Observable";
import {PaginationModel} from "../../widgets/pagination/pagination.component";

@Component({
  selector: 'app-fund-favorite',
  templateUrl: './fund-favorite.component.html',
  styleUrls: ['./fund-favorite.component.scss']
})
export class FundFavoriteComponent implements OnInit {

  /**
   * 个人组合分类列表内部私有源数据
   */
  private _fundFavoriteList: Array<FundFavoriteModel>;

  /**
   * 个人组合分类列表数据公开setter,调用的时候同时设置_fundFavoriteList和fundFavoriteFilterList，
   * 保证更新数据时，过滤数据与源数据保持一致,顺便清空已被选择的数据fundFavoriteSelectedList
   * @param {Array<FundFavoriteModel>} newValue
   */
  public set fundFavoriteList(newValue: Array<FundFavoriteModel>) {
    this._fundFavoriteList = this.fundFavoriteFilterList = newValue;
    this.fundFavoriteSelectedList = [];
  }

  /**
   * 个人组合分类列表数据公开getter
   * @returns {Array<FundFavoriteModel>}
   */
  public get fundFavoriteList(): Array<FundFavoriteModel> {
    return this._fundFavoriteList;
  }

  /**
   * 个人组合分类列表过滤数据
   */
  public fundFavoriteFilterList: Array<FundFavoriteModel>;

  /**
   * 个人组合分类列表被选择数据
   */
  public fundFavoriteSelectedList: Array<FundFavoriteModel>;

  /**
   * 个人组合分类下基金信息列表内部私有源数据
   */
  private _fundFavoriteDetailList: Array<FundFavoriteDetailModel>;

  /**
   * 个人组合分类下基金信息列表数据公开setter，调用的时候同时设置_fundFavoriteDetailList和fundFavoriteDetailList，
   * 保证更新数据时，过滤数据与源数据保持一致,顺便清空已被选择的数据fundFavoriteDetailSelectedList
   * @param {Array<FundFavoriteDetailModel>} newValue
   */
  public set fundFavoriteDetailList(newValue: Array<FundFavoriteDetailModel>) {
    this._fundFavoriteDetailList = this.fundFavoriteDetailFilterList = newValue;
    this.fundFavoriteDetailSelectedList = [];
  };

  /**
   * 个人组合分类下基金信息列表数据公开getter
   * @returns {Array<FundFavoriteDetailModel>}
   */
  public get fundFavoriteDetailList(): Array<FundFavoriteDetailModel> {
    return this._fundFavoriteDetailList;
  };

  /**
   * 个人组合分类下基金信息列表过滤数据
   */
  public fundFavoriteDetailFilterList: Array<FundFavoriteDetailModel>;


  /**
   * 个人组合分类下基金信息列表被选择的数据
   */
  public fundFavoriteDetailSelectedList: Array<FundFavoriteDetailModel>;

  /**
   * 用户有权访问的基金列表内部私有源数据
   */
  private _fundList: Array<FundModel>;

  /**
   * 用户有权访问的基金列表数据公开setter,调用的时候同时设置_fundList和fundList，
   * 保证更新数据时，过滤数据与源数据保持一致,顺便清空已被选择的数据fundSelectedList
   * @param {Array<FundModel>} newValue
   */
  public set fundList(newValue: Array<FundModel>) {
    this._fundList = this.fundFilterList = newValue;
    this.fundSelectedList = [];
  }

  /**
   * 用户有权访问的基金列表数据公开getter
   */
  public get fundList(): Array<FundModel> {
    return this._fundList;
  };

  /**
   * 用户有权访问的基金列表过滤数据
   */
  public fundFilterList: Array<FundModel>;

  /**
   * 用户有权访问的基金列表被选择的数据
   */
  public fundSelectedList: Array<FundModel>;

  /**
   * 当前选择的模块ID
   */
  public activedModelId: string;

  /**
   * 当前选择的模块名称
   */
  public activedModelName: string;

  /**
   * 当前选择的个人组合分类名称
   */
  public activedFavoriteName: string;

  /**
   * 当前选择的个人组合分类ID
   */
  public activedFavoriteId: string;

  /**
   * 当前登陆的用户ID
   */
  public userId: string;

  /**
   * 新增个人组合分类模态框绑定数据
   */
  public addFundFavoriteModalData: FundFavoriteModel = {
    objname: '',
    remark: '',
    sort: '',
    // TODO 临时固定为All
    model: 'ALL'
  };

  /**
   *修改个人组合分类模态框绑定数据
   */
  public modifyFundFavoriteModalData: FundFavoriteModel = {
    objid: '',
    objname: '',
    remark: '',
    sort: ''
  };

  /**
   * 个人组合分类列表当前分页信息
   */
  public fundFavoriteListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  /**
   * 个人组合分类下基金信息列表当前分页信息
   */
  public fundFavoriteDetailListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  /**
   * 用户有权访问的基金列表当前分页信息
   */
  public fundListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  @ViewChild('addFundFavoriteModal')
  public addFundFavoriteModal: ElementRef;

  @ViewChild('fundListRef')
  public fundListRef: ElementRef;

  @ViewChild('fundFavoriteListRef')
  public fundFavoriteListRef: ElementRef;

  @ViewChild('fundFavoriteDetailListRef')
  public fundFavoriteDetailListRef: ElementRef;

  constructor(public service: FundFavoriteService,
              public renderer: Renderer2) {
    this.userId = sessionStorage.getItem('username');
  }

  ngOnInit() {
    this.activedModelId = 'interbank';
    this.queryModelFundFavoriteList();
    this.queryAccessibleFundList();
  }

  /**
   * 根据模块ID和用户ID，查询指定模块下的【个人组合】的分类列表
   * @param {string} model
   * @param {string} userid
   * @param {number} page
   * @param {number} pageSize
   * @returns {Subscription}
   */
  public queryModelFundFavoriteList(model: string = this.activedModelId,
                                    userid: string = this.userId,
                                    page: number = this.fundFavoriteListPageInfo.currentPageNum,
                                    pageSize: number = this.fundFavoriteListPageInfo.pageSize): Subscription {
    // TODO model临时改为'ALL'，以后完善
    return this.service.queryModelFundFavoriteList('ALL', userid, page, pageSize)
      .subscribe((data) => {
        this.fundFavoriteList = (data != null) ? data.list : [];
        if (this.fundFavoriteList.length > 0) {
          this.queryFundFavoriteDetailList(this.fundFavoriteList[0].objid, this.fundFavoriteList[0].objname);
          this.fundFavoriteListPageInfo.totalPages = data.pages;
          this.fundFavoriteListPageInfo.total = data.total;
          this.fundFavoriteListPageInfo.startRow = data.startRow;
          this.fundFavoriteListPageInfo.endRow = data.endRow;
        }
      });
  }

  /**
   * 新增个人组合分类
   * @param {FundFavoriteModel} data
   * @param {string} userid
   * @returns {Subscription}
   */
  public insertFundFavorite(data: FundFavoriteModel = this.addFundFavoriteModalData, userid: string = this.userId): Subscription {
    return this.service.insertFundFavorite(data, userid).subscribe(() => {
      this.closeAddFundFavoriteModal();
      window['swal']({
        title: '提示',
        text: '新增个人组合分类成功！',
        type: 'success',
        html: true
      });
      this.queryModelFundFavoriteList();
    });
  }

  /**
   * 修改个人组合分类
   * @param {FundFavoriteModel} data
   * @param {string} userid
   * @returns {Subscription}
   */
  public updateFundFavorite(data: FundFavoriteModel = this.modifyFundFavoriteModalData, userid: string = this.userId): Subscription {
    return this.service.updateFundFavorite(data, userid).subscribe(() => {
      this.closeModifyFundFavoriteModal();
      window['swal']({
        title: '提示',
        text: '修改个人组合分类成功！',
        type: 'success',
        html: true
      });
      this.queryModelFundFavoriteList();
    });
  }

  /**
   * 根据【个人组合】分类的ID，查询出与其相钩稽的基金信息
   * @param {string} objid
   * @param {string} objname
   * @param {number} page
   * @param {number} pageSize
   * @returns {Subscription}
   */
  public queryFundFavoriteDetailList(objid: string,
                                     objname: string = this.activedFavoriteName,
                                     page: number = this.fundFavoriteDetailListPageInfo.currentPageNum,
                                     pageSize: number = this.fundFavoriteDetailListPageInfo.pageSize): Subscription {
    this.activedFavoriteId = objid;
    if (objname != null) {
      this.activedFavoriteName = objname;
    }
    return this.service.queryFundFavoriteDetailList(objid, page, pageSize)
      .subscribe((data) => {
        if (data != null && Array.isArray(data.list) && data.list.length > 0) {
          this.fundFavoriteDetailList = data.list;
          this.fundFavoriteDetailListPageInfo.totalPages = data.pages;
          this.fundFavoriteDetailListPageInfo.total = data.total;
          this.fundFavoriteDetailListPageInfo.startRow = data.startRow;
          this.fundFavoriteDetailListPageInfo.endRow = data.endRow;
        } else {
          this.fundFavoriteDetailList = [];
        }
      });
  }

  /**
   * 根据用户ID查询出其所有可以查看的权限组合／基金
   * @param {string} userid
   * @param {number} page
   * @param {number} pageSize
   * @returns {Subscription}
   */
  public queryAccessibleFundList(userid: string = this.userId,
                                 page: number = this.fundListPageInfo.currentPageNum,
                                 pageSize: number = this.fundListPageInfo.pageSize): Subscription {
    return this.service.queryAccessibleFundList(userid, page, pageSize)
      .subscribe((data) => {
        if (data != null && Array.isArray(data.list) && data.list.length > 0) {
          this.fundList = data.list.map((item) => {
            item.fundname = item['vc_fund_name'];
            item.fundcode = item['vc_fund_code'];
            delete item['vc_fund_name'];
            delete item['vc_fund_code'];
            return item;
          });
          this.fundListPageInfo.totalPages = data.pages;
          this.fundListPageInfo.total = data.total;
          this.fundListPageInfo.startRow = data.startRow;
          this.fundListPageInfo.endRow = data.endRow;
        } else {
          this.fundList = [];
        }
      });
  }

  /**
   * 根据数据列表源数据与列表模版映射对象，过滤出列表模版上已被选择的数据
   * @param {Array<any>} sourceData
   * @param {ElementRef} list
   * @returns {Array<any>}
   */
  public getSelectedDataList(sourceData: Array<any>, list: ElementRef): Array<any> {
    const data: Array<any> = [];
    const $list = Util.$(list.nativeElement);
    const $selectBtns = $list.find('[data-select-one="true"]');
    $selectBtns.each((index, item) => {
      if (item.checked) {
        data.push(sourceData[index]);
      }
    });
    return data;
  }

  /**
   * 新增个人组合明细数据
   * @param {Array<FundFavoriteDetailModel>} data
   * @returns {Observable<any>}
   */
  public addFundFavoriteDetail(data: Array<FundFavoriteDetailModel>): Observable<any> {
    return this.updateFundFavoriteDetail('ADD', this.activedFavoriteId, data);
  }


  /**
   * 将基金列表中已被选择的数据添加到个人组合分类明细列表中
   */
  public addFundListDetailToFavoriteDetail() {
    this.addFundFavoriteDetail(this.getSelectedDataList(this.fundList, this.fundListRef))
      .subscribe((data) => {
        Util.$(this.fundListRef.nativeElement).find('[data-select-all="true"]').prop('checked', false);
        this.toggleSelectAll(this.fundListRef);
        this.queryFundFavoriteDetailList(this.activedFavoriteId);
      });
  }

  /**
   * 删除个人组合明细数据
   * @param {Array} data
   * @returns {Observable<any>}
   */
  public deleteFundFavoriteDetail(data: Array<FundFavoriteDetailModel>): Observable<any> {
    return this.updateFundFavoriteDetail('DELETE', this.activedFavoriteId, data);
  }

  /**
   * 个人组合分类明细列表中已选择的数据删除
   */
  public deleteFundFavoriteDetailToFundList() {
    this.deleteFundFavoriteDetail(this.getSelectedDataList(this.fundFavoriteDetailList, this.fundFavoriteDetailListRef))
      .subscribe((data) => {
        Util.$(this.fundFavoriteDetailListRef.nativeElement).find('[data-select-all="true"]').prop('checked', false);
        this.toggleSelectAll(this.fundFavoriteDetailListRef);
        this.queryFundFavoriteDetailList(this.activedFavoriteId);
      });
  }

  /**
   * 更新（新增或删除）指定个人组合明细数据
   * @param {string} type 枚举值为 'ADD'和 'DELETE'
   * @param {string} objid
   * @param {Array<FundFavoriteDetailModel>} data
   * @returns {Observable<any>}
   */
  public updateFundFavoriteDetail(type: string, objid: string, data: Array<FundFavoriteDetailModel>): Observable<any> {
    return this.service.updateFundFavoriteDetail(type, objid, data);
  }

  /**
   * 清空指定文本框的值
   * @param selector
   */
  public clearInpusValue(selector: string) {
    const $ = Util.$;
    $(selector).each((index, item) => {
      $(item).val('');
    });
  }

  /**
   * 弹出删除个人组合分类明细数据询问模态框
   * @param {string} objid
   * @param {string} userid
   */
  public openDeleteFundFavoriteConfirmModal(objid: string, objname: string, userid: string = this.userId) {
    window['swal']({
        title: "提示",
        text: `是否删除<span class="text-warning">${objname}</span>`,
        type: "warning",
        html: true,
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "是",
        cancelButtonText: "否"
      },
      (isConfirm) => {
        if (isConfirm) {
          this.service.deleteFundFavorite(objid, userid).subscribe((data) => {
            window['swal']("提示", "删除成功！", "success");
            this.queryModelFundFavoriteList();
          });
        }
      });
  }

  /**
   * 重置新增个人组合分类模态框数据
   * @param {FundFavoriteModel} newData
   * @returns {FundFavoriteModel}
   */
  public resetAddFundFavoriteModalData(newData?: FundFavoriteModel): FundFavoriteModel {
    if (newData == null) {
      return this.addFundFavoriteModalData = {
        objname: '',
        remark: '',
        sort: '',
        // TODO 临时固定为All
        model: 'ALL'
      };
    }
    return this.addFundFavoriteModalData = newData;
  };

  /**
   * 重置修改个人组合分类模态框数据
   * @param {FundFavoriteModel} newData
   * @returns {FundFavoriteModel}
   */
  public resetModifyFundFavoriteModalData(newData?: FundFavoriteModel): FundFavoriteModel {
    if (newData == null) {
      return this.modifyFundFavoriteModalData = {
        objid: '',
        objname: '',
        remark: '',
        sort: '',
        // TODO 临时固定为All
        model: 'ALL'
      };
    }
    return this.modifyFundFavoriteModalData = newData;
  };

  /**
   * 打开新增个人组合模态框
   */
  public openAddFundFavoriteModal() {
    const $ = Util.$;
    const $modal = $('#addFundFavoriteModal');
    this.resetAddFundFavoriteModalData();
    $modal.modal('show');
  }

  /**
   * 关闭新增个人组合模态框
   */
  public closeAddFundFavoriteModal() {
    const $ = Util.$;
    const $modal = $('#addFundFavoriteModal');
    this.resetAddFundFavoriteModalData();
    $modal.modal('hide');
  }

  /**
   * 打开修改个人组合模态框
   * @param {FundFavoriteModel} data
   */
  public openModifyFundFavoriteModal(data: FundFavoriteModel) {
    const $ = Util.$;
    const $modal = $('#modifyFundFavoriteModal');
    this.modifyFundFavoriteModalData = Object.assign({}, data);
    return $modal.modal('show');
  }

  /**
   * 关闭修改个人组合模态框
   */
  public closeModifyFundFavoriteModal() {
    const $ = Util.$;
    const $modal = $('#modifyFundFavoriteModal');
    this.resetModifyFundFavoriteModalData();
    return $modal.modal('hide');
  }

  /**
   * 全选／全取消 指定模版上的选择框
   * @param {ElementRef} list
   */
  public toggleSelectAll(list: ElementRef) {
    const $list = Util.$((list instanceof ElementRef) ? list.nativeElement : list);
    const $selectAllBtn = $list.find('[data-select-all="true"]');
    const $selectOneBtns = $list.find('[data-select-one="true"]');
    if ($selectAllBtn.prop('checked')) {
      $selectOneBtns.each((index, item) => {
        Util.$(item).prop('checked', true);
      });
    } else {
      $selectOneBtns.each((index, item) => {
        Util.$(item).prop('checked', false);
      });
    }
  }


  /**
   * 根据页码请求查询个人组合分类列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param currentPageNum
   */
  public fundFavoriteListPageNavigation(currentPageNum: number) {
    this.fundFavoriteListPageInfo.currentPageNum = currentPageNum;
    this.queryModelFundFavoriteList(
      'ALL',
      this.userId,
      this.fundFavoriteListPageInfo.currentPageNum,
      this.fundFavoriteListPageInfo.pageSize);
  }

  /**
   * 改变个人组合分类列表每页显示记录数
   * @param pageSize
   */
  public fundFavoriteListPageSizeChange(pageSize: number) {
    if (pageSize !== this.fundFavoriteListPageInfo.pageSize) {
      this.fundFavoriteListPageInfo.pageSize = pageSize;
      this.fundFavoriteListPageInfo.currentPageNum = 1;
      this.queryModelFundFavoriteList('ALL', this.userId, 1, this.fundFavoriteListPageInfo.pageSize);
    }
  }

  /**
   * 根据页码请求查询用户有权访问的基金列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param currentPageNum
   */
  public fundListPageNavigation(currentPageNum: number) {
    this.fundListPageInfo.currentPageNum = currentPageNum;
    this.queryAccessibleFundList(
      this.userId,
      this.fundListPageInfo.currentPageNum,
      this.fundListPageInfo.pageSize);
  }

  /**
   * 改变用户有权访问的基金列表每页显示记录数
   * @param pageSize
   */
  public fundListPageSizeChange(pageSize: number) {
    if (pageSize !== this.fundListPageInfo.pageSize) {
      this.fundListPageInfo.pageSize = pageSize;
      this.fundListPageInfo.currentPageNum = 1;
      this.queryAccessibleFundList(this.userId, 1, this.fundListPageInfo.pageSize);
    }
  }

  /**
   * 根据页码请求查询个人组合分类下基金信息列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param currentPageNum
   */
  public fundFavoriteDetailListPageNavigation(currentPageNum: number) {
    this.fundFavoriteDetailListPageInfo.currentPageNum = currentPageNum;
    this.queryFundFavoriteDetailList(
      this.activedFavoriteId,
      this.activedFavoriteName,
      this.fundFavoriteDetailListPageInfo.currentPageNum,
      this.fundFavoriteDetailListPageInfo.pageSize);
  }

  /**
   * 改变个人组合分类下基金信息列表每页显示记录数
   * @param pageSize
   */
  public fundFavoriteDetailListPageSizeChange(pageSize: number) {
    if (pageSize !== this.fundFavoriteDetailListPageInfo.pageSize) {
      this.fundFavoriteDetailListPageInfo.pageSize = pageSize;
      this.fundFavoriteDetailListPageInfo.currentPageNum = 1;
      this.queryFundFavoriteDetailList(this.activedFavoriteId, this.activedFavoriteName, 1, this.fundFavoriteDetailListPageInfo.pageSize);
    }
  }

}
